package com.it.test4case2;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

public class MyThread extends Thread {
    //共享数据
    //红包的金额，3个红包
    //最小红包数0.01
    static BigDecimal money = BigDecimal.valueOf(100,0);
    static int count = 3;
    static final BigDecimal MIX = BigDecimal.valueOf(0.01);
    public void run(){
        //同步代码块
        synchronized(MyThread.class){
            //判断是否有红包
            if(count == 0){
                System.out.println(getName()+"没有抢到红包");
            }else{
            //抢到了红包，随机红包的金额（第一次，第二次）
                BigDecimal prize;
                if(count == 1){
                    prize = money;
                }else{
                    //随机红包金额
                    Random r = new Random();
                    //最大红包范围，最坏的情况就是两个0.01，和99.98
                    double bounds = money.subtract(BigDecimal.valueOf(count-1).multiply(MIX)).doubleValue();
                    prize = BigDecimal.valueOf(r.nextDouble(bounds));
                }
                //设置抽到红包，小数点保留两位，四舍五入
                prize = prize.setScale(2, RoundingMode.CEILING);
                //在总金额中去掉对应的钱
                money = money.subtract(prize);
                //红包-1
                count--;
                System.out.println(getName()+"抢到了"+prize+"元");
            }
        }
    }
}
